package com.rcloud.server.sealtalk.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rcloud.server.sealtalk.constant.ErrorCode;
import com.rcloud.server.sealtalk.controller.param.FaceAuthParam;
import com.rcloud.server.sealtalk.domain.Users;
import com.rcloud.server.sealtalk.exception.ServiceException;
import com.rcloud.server.sealtalk.manager.FaceAuthManager;
import com.rcloud.server.sealtalk.model.response.APIResult;
import com.rcloud.server.sealtalk.model.response.APIResultWrap;
import com.rcloud.server.sealtalk.model.tencent.Geth5faceidVo;
import com.rcloud.server.sealtalk.service.FaceVerificationService;
import com.rcloud.server.sealtalk.service.UsersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * @author xiaochaoge
 * @title: FaceAuthController
 * @projectName sealtalk-server
 * @description: TODO
 * @date 2022/3/214:53
 */
@Slf4j
@Api(tags = "腾讯人脸识别相关接口")
@RestController
@RequestMapping("/tencent/face/")
public class FaceAuthController extends BaseController {

    @Autowired
    private FaceVerificationService faceVerificationService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private FaceAuthManager faceAuthManager;

    /**
     * 人脸识别认证
     */
    @PostMapping(value = "/faceAuth")
    @ApiOperation(value = "腾讯人脸识别认证", notes = "腾讯人脸识别认证")
    public APIResult<Object> faceAuth(@Valid @RequestBody FaceAuthParam param) throws ServiceException {
        // postType  1 代表腾讯的认证  2 代表百度的认证
        Boolean result = faceAuthManager.faceAuthHandle(param, getCurrentUserId(),1);
        return APIResultWrap.ok(result);
    }


    @ApiOperation(value = "SDK获取Sign接口信息", notes = "SDK获取Sign接口信息")
    @GetMapping(path = "/getSign")
    @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String", required = true)
    public APIResult<Object> getSign(@RequestParam(required = false) String userId) throws ServiceException {
        //判断参数是否上传
        if (userId == null) {
            throw new ServiceException(ErrorCode.TENCENT_USERID_NOT_EMPTY);
        }
        String faceNonceTicket = faceVerificationService.getFaceNonceTicket(userId);
        //获取上送信息的参数集合
        Map<String, String> verificationSign = faceVerificationService.getFaceVerificationSign(userId, faceNonceTicket);
        log.info("上送信息请求参数 {}", verificationSign.toString());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", userId);
        jsonObject.put("nonce", verificationSign.get("nonce"));
        jsonObject.put("sign", verificationSign.get("sign"));
        return APIResultWrap.ok(jsonObject);
    }

    @ApiOperation(value = "合作方后台上送身份信息", notes = "合作方后台上送身份信息")
    @PostMapping(path = "/getFaceId")
    public APIResult<Object> getFaceId() throws ServiceException {
        Integer currentUserId = getCurrentUserId();
        Users loginUser = usersService.getByPrimaryKey(currentUserId);
        //判断用户是否存在
        if (loginUser == null) {
            throw new ServiceException(ErrorCode.USER_NOT_EXIST);
        }
        //判断当前用户是否实名认证
        if (loginUser.getIsReal() == 0) {
            throw new ServiceException(ErrorCode.USER_NOT_AUTH_ERROR);
        }
        //获取上送信息的参数集合
        Geth5faceidVo faceidVo = faceVerificationService.getFaceVerificationSignMap(loginUser.getIdentitycard(), loginUser.getName());
        log.info("getFaceId 入参 {}", faceidVo.toString());
        String url = "https://miniprogram-kyc.tencentcloudapi.com/api/server/getfaceid?orderNo=" + faceidVo.getOrderNo();
        JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(faceidVo));
        log.info("上送信息请求参数 {}", itemJSONObj.toString());
        String resp = HttpUtil.post(url, itemJSONObj.toJSONString());
        log.info("上送信息返回参数 {}", resp);
        JSONObject jsonObject = JSON.parseObject(resp);
        jsonObject.put("userId", faceidVo.getUserId());
        return APIResultWrap.ok(jsonObject);
    }
}
